<script setup lang="ts">
import formButton from '@renderer/components/formButton.vue'
import NavBar from '@renderer/components/navBar.vue'
import useCompute from '@renderer/composables/useCompute'
import useComputeForm from '@renderer/composables/useComputeForm'
import helper from '@renderer/utils/helper'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter()
const pageQuery = route.currentRoute.value.query
const initSubmitForm = () => ({
  name: '',
  number: '',
  unit_price: '',
  remark: '',
  unit: '',
})
const submitForm = reactive(initSubmitForm())
const addDataDialog = ref(false)
const changeRow = ref<any[]>([])
const ids = ref([])
const selectType = ref<number>(0)
const total = computed(() => {
  return ((submitForm.unit_price as any) * 1 * ((submitForm.number as any) * 1)).toFixed(2)
})
const handleClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  selectType.value = 0
  addDataDialog.value = false
  await initPage()
}
const handleAddData = async (type: number) => {
  if (changeRow.value.length) {
    const { type } = await getTableDataType({ name: pageQuery.name })
    await handleSaveTableData(changeRow.value, type!)
    changeRow.value = []
  }
  selectType.value = type
  addDataDialog.value = true
}
const handleExport = async (type) => {
  const res = await exportSettleTable({
    calculate_id: pageQuery.calculate_id,
    name: pageQuery.name,
    type,
  })
  downLoadFile(res, '结算单.xlsx')
}
const handleSave = async () => {
  if (!submitForm.name) {
    ElMessage.error('项目名称不能为空')
    return
  }
  if (!submitForm.unit_price) {
    ElMessage.error('单价不能为空')
    return
  }
  if (!submitForm.number) {
    ElMessage.error('数量不能为空')
    return
  }
  if (!submitForm.unit) {
    ElMessage.error('单位不能为空')
    return
  }
  await addCostDetailData({
    calculate_id: pageQuery.calculate_id,
    type_name: pageQuery.name,
    type: selectType.value,
    name: submitForm.name,
    unit: submitForm.unit,
    unit_price: submitForm.unit_price,
    remark: submitForm.remark,
    number: submitForm.number,
  })
  handleClose()
}
const handleBlueCompute = (newVal: CostInfo, index: number, isCompute: boolean = false) => {
  if (isCompute) {
    const childIndex = costBalanceList.value![index].list.findIndex((childItem) => childItem.name == newVal.name)
    if (childIndex != -1) {
      costBalanceList.value![index].list[childIndex].total_price =
        (Number(newVal.number) * Number(newVal.unit_price)).toFixed(2) + ''
      const totalIndex = costBalanceList.value![index].list.findIndex((childItem) => childItem.name == '合计')
      if (totalIndex != -1) {
        costBalanceList.value![index].list[totalIndex].total_price = '0'
        costBalanceList.value![index].list.forEach((item) => {
          if (item.name != '合计') {
            costBalanceList.value![index].list[totalIndex].total_price =
              (Number(costBalanceList.value![index].list[totalIndex].total_price) + Number(item.total_price)).toFixed(
                2,
              ) + ''
          }
        })
      }
    }
  }
  if (!changeRow.value.includes(newVal)) {
    changeRow.value.push(newVal)
  } else {
    changeRow.value = changeRow.value.filter((item) => item !== newVal)
    changeRow.value.push(newVal)
  }
}
const handleRefresh = async () => {
  // ElMessageBox.alert('提交修改需要手动保存数据，请确认您已保存数据。', '温馨提示', {
  //   showCancelButton: true,
  //   callback: async (action: Action) => {
  //     if (action == 'confirm') {

  //     }
  //   },
  // })
  if (changeRow.value.length) {
    const { type } = await getTableDataType({ name: pageQuery.name })
    await handleSaveTableData(changeRow.value, type!)
    changeRow.value = []
  }
  await resetInter({
    calculate_id: pageQuery.calculate_id,
  })
  await initPage()
  window.api.refreshCostData(Number(pageQuery.house_type))
}
const handleSaveData = async () => {
  const { type } = await getTableDataType({ name: pageQuery.name })
  await handleSaveTableData(changeRow.value, type!)
  await initPage()
  changeRow.value = []
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
}
const selectable = (row: InfoListModel) => {
  if (row.name == '合计') {
    return false
  } else {
    return true
  }
}
const handleDelData = async () => {
  if (changeRow.value.length) {
    ElMessage({ type: 'error', message: '你有未保存的数据，请先保存数据在进行删除此项目。' })
    return
  }
  if (ids.value.length) {
    const { type } = await getTableDataType({ name: pageQuery.name })
    await delTableData({
      calculate_id: pageQuery.calculate_id,
      ids: ids.value,
      type: type,
    })
    await getCostCateDetailRecord({
      calculate_id: pageQuery.calculate_id,
      name: pageQuery.name,
      client_type: 'GUI',
    })
  } else {
    ElMessage({ type: 'error', message: '请选择要删除的数据' })
  }
}
const handleRoomName = (cate_name, house_number) => {
  if ((pageQuery.house_number as any) * 1 > 1 && (pageQuery.name == '瓷砖' || pageQuery.name == '成品定制')) {
    switch (house_number * 1) {
      case 1:
        return '一层' + cate_name
      case 2:
        return '二层' + cate_name
      case 3:
        return '三层' + cate_name
      case 4:
        return '四层' + cate_name
      case 5:
        return '五层' + cate_name
      default:
        return cate_name
    }
  } else {
    return cate_name
  }
}
const initPage = async () => {
  await getCostCateDetailRecord({
    calculate_id: pageQuery.calculate_id,
    name: pageQuery.name,
    client_type: 'GUI',
  })
}
const { getCostCateDetailRecord, costBalanceList, addCostDetailData, exportSettleTable, resetInter, getTableDataType } =
  useCompute()
const { handleSaveTableData, downLoadFile, checkRule } = helper()
const { delTableData } = useComputeForm()
await initPage()
</script>

<template>
  <main class="bg-white flex flex-col nodrag overflow-hidden" style="height: -webkit-fill-available">
    <div
      class="px-6 h-[50px] border-b flex items-center bg-white gap-3"
      style="width: -webkit-fill-available"
      v-if="checkRule('成本明细修改权')">
      <formButton @click="handleSaveData">保存数据</formButton>
      <formButton @click="handleRefresh">提交修改</formButton>
      <formButton @click="handleDelData" v-if="ids.length">删除数据</formButton>
    </div>
    <section class="flex flex-col gap-4 py-6 overflow-y-auto flex-1">
      <div class="flex flex-col">
        <div class="text-center font-bold text-2xl text-black mt-2 mb-1">{{ pageQuery.name }}结算单</div>
        <div class="text-center text-sm text-[#888888]">工程地址：{{ pageQuery.calculate_name }}</div>
      </div>
      <div class="flex flex-col gap-5 px-6">
        <div class="flex flex-col gap-2" v-for="(item, index) in costBalanceList" :key="index">
          <div class="flex justify-between items-center">
            <span class="text-base text-black"> {{ index + 1 }}、{{ item.title }}</span>
            <div class="flex gap-3 items-center">
              <formButton @click="handleExport(item.type)">导出数据</formButton>
              <formButton @click="handleAddData(item.type)">添加项目</formButton>
            </div>
          </div>
          <el-table
            :data="item.list"
            border
            header-align="center"
            @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }">
            <el-table-column type="selection" width="40" align="center" :selectable="selectable" />
            <el-table-column type="index" label="序号" align="center" width="55" />
            <el-table-column prop="name" label="项目名称" align="center" width="180">
              <template #default="scope">
                <template v-if="scope.row.name != '合计'">
                  {{ handleRoomName(scope.row.name, scope.row.house_number) }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" align="center" width="80">
              <template #default="scope">
                <el-input
                  v-model="scope.row.unit"
                  v-if="scope.row.name != '合计' && checkRule('成本明细修改权')"
                  @input="handleBlueCompute(scope.row, index)" />
              </template>
            </el-table-column>
            <el-table-column prop="number" label="数量" align="center" width="85">
              <template #default="scope">
                <el-input
                  v-model="scope.row.number"
                  v-if="scope.row.name != '合计' && checkRule('成本明细修改权')"
                  type="number" @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, index, true)" />
              </template>
            </el-table-column>
            <el-table-column prop="unit_price" label="单价" align="center" width="100">
              <template #default="scope">
                <el-input
                  v-model="scope.row.unit_price"
                  v-if="scope.row.name != '合计' && checkRule('成本明细修改权')"
                  type="number" @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, index, true)" />
              </template>
            </el-table-column>
            <el-table-column prop="brick_width" label="砖宽" align="center" width="80" v-if="pageQuery.name == '瓷砖'">
              <template #default="scope">
                <el-input
                  v-model="scope.row.brick_width"
                  v-if="scope.row.name != '合计' && checkRule('成本明细修改权')"
                  type="number" @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, index)" />
              </template>
            </el-table-column>
            <el-table-column prop="brick_long" label="砖长" align="center" width="80" v-if="pageQuery.name == '瓷砖'">
              <template #default="scope">
                <el-input
                  v-model="scope.row.brick_long"
                  v-if="scope.row.name != '合计' && checkRule('成本明细修改权')"
                  type="number" @mousewheel.native.prevent
                  @input="handleBlueCompute(scope.row, index)" />
              </template>
            </el-table-column>
            <el-table-column prop="total_price" label="合计" align="center" width="100" />
            <el-table-column prop="remark" label="备注" align="center">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  v-if="scope.row.name != '合计' && checkRule('成本明细修改权')"
                  @input="handleBlueCompute(scope.row, index)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <el-dialog v-model="addDataDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleClose" title="新增项目数据" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6" label-width="90">
          <el-form-item label="项目名称:" required>
            <el-input v-model="submitForm.name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="单位:" required>
            <el-input v-model="submitForm.unit" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="数量:" required>
            <el-input v-model="submitForm.number" placeholder="请输入" clearable type="number" @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="单价:" required>
            <el-input v-model="submitForm.unit_price" placeholder="请输入" clearable type="number" @mousewheel.native.prevent />
          </el-form-item>
          <el-form-item label="合计:" required>
            <el-input v-model="total" placeholder="请输入" clearable readonly />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="submitForm.remark" placeholder="请输入" clearable />
          </el-form-item>
          <div class="flex justify-center" @click="handleSave">
            <div class="save-button">提交</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
  flex: 1;
}
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
</style>
